<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\contract;

use app\common\dao\contract\ContractLesseeDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
use app\common\repositories\users\UsersRepository;
use think\facade\Db;

/**
 * Class ContractLesseeRepository
 *
 * @mixin ContractLesseeDao
 */
class ContractLesseeRepository extends BaseRepository
{

    public function __construct(ContractLesseeDao $dao)
    {
        $this->dao = $dao;
    }

    public function addLesseeInfo(array $data, int $propertyId)
    {
        $data['property_id'] = $propertyId;
        return $this->dao->create($data);
    }


    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'userInfo' => function ($query) {
                    $query->field('id,mobile');
                    $query->bind(['mobile' => 'mobile']);
                }
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    /**
     *  根据合同ID 获取用户
     * @param array $where
     * @param $page
     * @param $limit
     * @param int|null $propertyId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-13 23:09
     */
    public function getContractIdList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'userInfo' => function ($query) {
                    $query->field('id,mobile');
                    $query->bind(['mobile' => 'mobile']);
                }
            ])
            ->field('id,contract_id,user_id,username,is_type,number,status,remark,is_owner,front_file,back_file')
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }


    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {

            /** @var UsersRepository $userRepository */
            $userRepository = app()->make(UsersRepository::class);
            $userInfo = $userRepository->getInfoByMobile($data['mobile']);
            if (!$userInfo) {
                $userdData['mobile'] = $data['mobile'];
                $userdData['account'] = $data['mobile'];
                $userdData['username'] = $data['username'];
                $userInfo = $userRepository->register($userdData);
            }

            $data['property_id'] = $propertyId;
            $data['user_id'] = $userInfo['id'];
            $res = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'CONTRACT.LESSEE.ADD', $data);
            return $res;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            /** @var UsersRepository $userRepository */
            $userRepository = app()->make(UsersRepository::class);
            $userInfo = $userRepository->getInfoByMobile($data['mobile']);
            if (!$userInfo) {
                $userdData['mobile'] = $data['mobile'];
                $userdData['account'] = $data['mobile'];
                $userdData['username'] = $data['username'];
                $userInfo = $userRepository->register($userdData);
            }
            unset($data['mobile']);
            if ($info['user_id'] != $userInfo['user_id']) {
                $data['user_id'] = $userInfo['id'];
            }
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'CONTRACT.LESSEE.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }


    public function getDetail(int $id)
    {
        $data = $this->dao->getSearch([])
            ->with([
                'userInfo' => function ($query) {
                    $query->field('id,mobile');
                    $query->bind(['mobile' => 'mobile']);
                }
            ])
            ->where('id', $id)
            ->find();
        return $data;
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        /** @var PropertyUsersLogRepository $repository */
        $repository = app()->make(PropertyUsersLogRepository::class);
        $repository->addInfo($info['property_id'], $userId, 'CONTRACT.LESSEE.DEL', $info);
        $this->dao->delete($info['id']);
    }


}